/****************************
 * 名称：微服务
 * 功能：接口服务框架
 ****************************/

/**
 * 导入需要的第三方模块
 **/
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require('path')
var cors = require('cors')


/**
 * 获取配置信息
 **/
global.config = require('./config').configInfo;

/**
 * 创建公共全局变量
 **/
global.log4js = require('log4js');
global.async = require('async');
global.RES = require('./framework/lib/response');
global.R = require('./framework/lib/request');
global.MESSAGE = require('./framework/message/systemMessage');
global.common = require('./framework/lib/commonFunc');
global.V = require('./framework/lib/verification');
global.regexpRule = require("./framework/lib/regexpConfig").regexpRule;
global.request = require('request');
global.db = require('./framework/lib/db');
global.APIConfig = require('./' + config.server.businessPath + '/api/api');
global.F = require('./framework/lib/processControl');
global.Render = require('./framework/lib/viewRender');

//本地接口请求服务地址
global.LocalServer = config.server.ip + ":" + config.server.port;

global.socketUser = {}//连接socket的所有用户
global.chatRoom = {}//所有的聊天室信息
global.namespaceName = ''//用户所在命名空间
global.userSocket = ''//用户Socket


//判断API文件是否存在，存在
var exists = fs.existsSync(__dirname + "/" + config.server.businessPath);
if (exists) {
	global.APIConfig = require('./' + config.server.businessPath + '/api/api');
} else {
	console.log('提示：您还没有创建业务目录,所有请求接口都将转发至核心层进行处理');
	global.APIConfig = { API: {} };
}


//合并系统内置接口配置
var systemApi = require('./framework/api/systemApi');
for (var k in systemApi.systemApi) {
	global.APIConfig.API[k] = systemApi.systemApi[k]
}

/**
 * 创建局部工具变量
 **/
var urlFilter = require("./framework/lib/urlFilter");
var urlParse = require("./framework/lib/urlParse");

/**
 * 创建sqlite全局操作对象
 **/
var sqlite3 = require('sqlite3').verbose();
global.sqliteDb = new sqlite3.Database(config.sqlit.dbPath);

/**
 * 生成http服务对象
 **/
global.app = express();

//设置所使用的模板引擎，以及模板所在位置
app.set('views', path.join(__dirname, '/docs/views'));
app.set('view engine', 'ejs');


/**
 * 加载中间件部分
 **/
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('file'));
app.use(express.static('public'));


/**
 * 图片处理全局对象
 **/
global.GM = require('gm').subClass({ imageMagick: true })

/**
 * URL检测
 **/
app.all("*", function (req, res, next) {
	urlFilter['Url'](req, res, next);
});


/**
 * 设置默认路由地址,
 **/
app.all("/",function(req,res,next){
	res.redirect('/index');
});



/**
 * ec_web_api接口路由部分
 * urlParse.APIisExist  		  : 查看该接口是否存在
 * urlParse.APIisMethod  		  : 查看该接口请求方式是否正确
 * urlParse.APIgetParams 		  : 解析接口参数信息
 * urlParse.APIParamsVerification : 参数格式验证
 **/
app.all(["/","/:firstMenuLevel","/:firstMenuLevel/:secondMenuLevel/*", "/:firstMenuLevel/:secondMenuLevel"],
	urlParse.APIBaseParamsVerification,
	urlParse.APIisExist,
	urlParse.APIisMethod,
	urlParse.APIgetParams,
	urlParse.APIParamsVerification,
	function (req, res) {

		var route = null;

		//根据接口类型进行不一样的路由处理
		if(req.routeInfo.apiType == 'SYSTEM'){

			if(req.routeInfo.isView){

				var routePath = "./framework/routes/" + req.routeInfo.apiRoute;

				route = require(routePath);

				var fileName = path.basename(routePath);

				route[fileName](req,res);

			}else{

				//获取请求路由
				route = require("./framework/routes/" + req.routeInfo.apiFullName);

				route[req.routeInfo.secondMenuLevelName](req,res);

			}


		}else {

			if(req.routeInfo.isView){

				var routePath = "./framework/routes/" + req.routeInfo.apiRoute;

				route = require(routePath);

				var fileName = path.basename(routePath);

				route[fileName](req,res);

			}else{

				//获取请求路由
				route = require("./" + config.server.businessPath + "/routes/" + req.routeInfo.apiFullName);

				route[req.routeInfo.secondMenuLevelName](req,res);

			}

		}

	});

app.all('*', function (req, res) {
	res.end('该接口不存在，请重新确认');
});


/**
 * 启动服务器
 **/

var server = http.createServer(app);
global.io = require('socket.io').listen(server);
server.listen(config.server.port, function () {
	console.log('服务器正常启动...端口号:' + 8007);
	global.socketObj = require('./socket/socket.class').Socket
	require('./socket/index');
});